package com.market.fleamarket.controller;

import com.market.fleamarket.entity.User;
import com.market.fleamarket.service.UserService;
import com.market.fleamarket.dto.LoginRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.HashMap;
import java.util.UUID;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Object register(@RequestBody User user) {
        try {
            return userService.register(user);
        } catch (Exception e) {
            return java.util.Collections.singletonMap("error", e.getMessage());
        }
    }

    @PostMapping("/login")
    public Object login(@RequestBody LoginRequest request, HttpSession session) {
        try {
            User user = userService.loginWithStatusCheck(request.getUsername(), request.getPassword());
            session.setAttribute("user", user);
            session.setAttribute("userRole", user.getRole());
            return java.util.Collections.singletonMap("msg", "登录成功");
        } catch (Exception e) {
            return java.util.Collections.singletonMap("error", e.getMessage());
        }
    }

    @PostMapping("/guest-login")
    public Map<String, Object> guestLogin(HttpSession session) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 创建临时游客用户
            User guestUser = new User();
            String guestUsername = "游客_" + UUID.randomUUID().toString().substring(0, 8);
            guestUser.setId(-1L); // 使用负数ID表示临时用户
            guestUser.setUsername(guestUsername);
            guestUser.setPassword("guest_password"); // 设置一个占位密码，避免空值问题
            guestUser.setRole("guest");

            // 保存到会话
            session.setAttribute("user", guestUser);
            session.setAttribute("userRole", "guest");

            // 只返回必要的用户信息，避免序列化问题
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", -1);
            userInfo.put("username", guestUsername);
            userInfo.put("role", "guest");

            response.put("success", true);
            response.put("msg", "已以游客身份登录");
            response.put("user", userInfo);
        } catch (Exception e) {
            response.put("success", false);
            response.put("error", "游客登录失败: " + e.getMessage());
        }

        return response;
    }

    @GetMapping("/me")
    public User getCurrentUser(HttpSession session) {
        return (User) session.getAttribute("user");
    }

    @GetMapping("/{username}")
    public User getUserByUsername(@PathVariable String username) {
        return userService.findByUsername(username).orElse(null);
    }

    @PostMapping("/update-password")
    public Map<String, String> updatePassword(@RequestBody Map<String, String> request, HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                throw new RuntimeException("请先登录");
            }

            // 游客不能修改密码
            if ("guest".equals(currentUser.getRole())) {
                throw new RuntimeException("游客用户不能修改密码");
            }

            String oldPassword = request.get("oldPassword");
            String newPassword = request.get("newPassword");
            String confirmPassword = request.get("confirmPassword");

            if (oldPassword == null || newPassword == null || confirmPassword == null) {
                throw new RuntimeException("请填写所有必填字段");
            }

            if (!newPassword.equals(confirmPassword)) {
                throw new RuntimeException("新密码与确认密码不匹配");
            }

            User updatedUser = userService.updatePassword(currentUser.getId(), oldPassword, newPassword);

            // 更新会话中的用户信息
            session.setAttribute("user", updatedUser);

            return java.util.Collections.singletonMap("msg", "密码修改成功");
        } catch (Exception e) {
            return java.util.Collections.singletonMap("error", e.getMessage());
        }
    }

    @PostMapping("/update-profile")
    public Map<String, Object> updateProfile(@RequestBody Map<String, String> request, HttpSession session) {
        Map<String, Object> response = new HashMap<>();

        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                throw new RuntimeException("请先登录");
            }

            // 游客不能修改个人信息
            if ("guest".equals(currentUser.getRole())) {
                throw new RuntimeException("游客用户不能修改个人信息");
            }

            String username = request.get("username");
            String phoneNumber = request.get("phoneNumber");

            // 检查用户名是否已存在
            if (username != null && !username.equals(currentUser.getUsername())) {
                User existingUser = userService.findByUsername(username).orElse(null);
                if (existingUser != null) {
                    throw new RuntimeException("用户名已存在！");
                }
            }

            User updatedUser = userService.updateProfile(currentUser.getId(), username, phoneNumber);

            // 更新会话中的用户信息
            session.setAttribute("user", updatedUser);

            response.put("success", true);
            response.put("msg", "个人信息更新成功");
            response.put("user", updatedUser);

            return response;
        } catch (Exception e) {
            response.put("success", false);
            response.put("error", e.getMessage());
            return response;
        }
    }
} 